#include "pipelib.h"
#include <unistd.h>  // 补充getpid所需头文件

int main() {
    int server_fifo_fd;
    int client_fifo_fd;
    int res;
    char client_fifo_name[NAME_SIZE];
    message msg;

    msg.client_pid = getpid();
    
    // 使用snprintf确保安全，补充格式控制符
    snprintf(client_fifo_name, NAME_SIZE, "%s_%d", CLIENT_FIFO_NAME, msg.client_pid);

    if (mkfifo(client_fifo_name, 0666) == -1) {  // 修改权限为更合理的0666
        fprintf(stderr, "Sorry, create client fifo failure!\n");
        return -1;
    }

    server_fifo_fd = open(SERVER_FIFO_NAME, O_WRONLY);
    if (server_fifo_fd == -1) {
        fprintf(stderr, "Sorry, open server fifo failure!\n");
        return -1;
    }

    sprintf(msg.data, "Hello from %d", msg.client_pid);
    printf("%d sent %s \n", msg.client_pid, msg.data);
    write(server_fifo_fd, &msg, sizeof(msg));

    client_fifo_fd = open(client_fifo_name, O_RDONLY);
    if (client_fifo_fd == -1) {
        fprintf(stderr, "Sorry, client fifo open failure!\n");
        close(server_fifo_fd);  // 增加错误时的资源释放
        return -1;
    }

    res = read(client_fifo_fd, &msg, sizeof(msg));
    if (res > 0) {
        printf("received:%s\n", msg.data);
    }

    close(client_fifo_fd);
    close(server_fifo_fd);
    unlink(client_fifo_name);
    return 0;
}
